package cn.nexttec.noteplayer.ui.activities

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.nexttec.noteplayer.R
import cn.nexttec.noteplayer.common.TAG
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.common.gson
import cn.nexttec.noteplayer.databinding.ActivitySearchBinding
import cn.nexttec.noteplayer.ui.adapters.NoteAdapter
import cn.nexttec.noteplayer.ui.adapters.VideoFileAdapter
import cn.nexttec.noteplayer.viewmodels.SearchViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.handleCoroutineException

enum class SearchMode {
    VIDEO,
    NOTE
}

@AndroidEntryPoint
class SearchActivity : AppCompatActivity() {
    private var canSearch = true
    private var lastScrollPosition: Int = 0
    private lateinit var _binding: ActivitySearchBinding
    private val binding get() = _binding
    private var searchMode = SearchMode.VIDEO
    private val handler = Handler(Looper.getMainLooper())
    private lateinit var adapter: RecyclerView.Adapter<*>
    private lateinit var layoutManager: LinearLayoutManager
    private var isTopFiles = true

    private val viewModel: SearchViewModel by viewModels()

    companion object {
        fun startActivity(context: Context, mode: Int = 0) {
            val intent = Intent(context, SearchActivity::class.java)
            intent.putExtra("search", mode)
            context.startActivity(intent)
        }
    }

    private val timer = object : CountDownTimer(1000, 100) {
        override fun onTick(millisUntilFinished: Long) {

        }

        override fun onFinish() {
            search()
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivitySearchBinding.inflate(layoutInflater)
        setContentView(binding.root)
        window.statusBarColor = ContextCompat.getColor(this, R.color.lt_blue)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        layoutManager = LinearLayoutManager(this)
        val mode = intent.getIntExtra("search", 0)
        searchMode = if (mode == 0) SearchMode.VIDEO else SearchMode.NOTE
        if (searchMode == SearchMode.VIDEO) {
            adapter = VideoFileAdapter()
            (adapter as VideoFileAdapter)?.onItemClick = {
                TAG debug "click ${it.gson()}"
                if (it.isDirectory) {
                    lastScrollPosition = layoutManager.findFirstVisibleItemPosition()
                    viewModel.loadDirectory(it)
                } else {
                    PlayerActivity.start(this, it)
                }
            }
        } else {
            adapter = NoteAdapter(
                onItemClicked = {
                    val intent = Intent(this, EditorActivity::class.java)
                    intent.putExtra("note", it)
                    startActivity(intent)
                }
            )
        }

        binding.etKeyword.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE){
                search()
                true
            } else {
                false
            }
        }

        binding.etKeyword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                timer.cancel()
            }

            override fun afterTextChanged(s: Editable?) {
                if ((s?.length ?: 0) > 0) {
                    timer.start()
                }
            }

        })

        viewModel.fileResult.observe(this) {
            if (::adapter.isInitialized){
                with(adapter as VideoFileAdapter) {
                    clear()
                    setVideoFiles(it, false)
                }
            }
        }

        viewModel.noteResult.observe(this){
            if (::adapter.isInitialized){
                with(adapter as NoteAdapter){
                    appendNotes(it)
                }
            }
        }
    }




    private fun search() {
        if (!canSearch){
            return
        }
        canSearch = false
        handler.postDelayed({canSearch = true},1500)
        val keyword = binding.etKeyword.text.toString()
        if (keyword.isNotBlank()) {
            viewModel.searchVideo(keyword)
        }
    }
}